package v1

import (
	"fmt"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
)

// 新增点赞
func AddPriase(c *gin.Context)  {
	// 引入结构体
	var data model.Praise
	_ = c.ShouldBindJSON(&data)
	uid,_ := c.Get("userid")
	data.Uid = uid.(int)

	// 判断文章是否存在
	_,code := model.GetArtInfo(data.Aid)
	if code != errmsg.SUCCSE{
		c.JSON(http.StatusOK, gin.H{
			"status":code,
			"message":errmsg.GetErrorMsg(code),
		})
		return
	}

	praiseArt,code := model.IsPraiseArt(data.Uid,data.Aid)

	// 点赞
	if data.Status == 0{
		if code == errmsg.ERROR{
			code = model.CreatePraise(&data) // 没有数据，点赞成功
			model.IncrArtPriase(data.Aid)
		}else{
			if praiseArt.Status == 1 {
				model.SavePraise(&data,data.Uid) //
				model.IncrArtPriase(data.Aid)
			}
		}
	}else{
		// 取消点赞
		if code == errmsg.SUCCSE{
			if praiseArt.Status == 0{
				model.SavePraise(&data,data.Uid) //
				model.SubArtPriase(data.Aid)
			}
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"status":code,
		"message":errmsg.GetErrorMsg(code),
	})

}

// 新增评论点赞
func AddCommentPraise(c *gin.Context){
	// 引入结构体
	var data model.CommentPraise
	_ = c.ShouldBindJSON(&data)
	uid,_ := c.Get("userid")
	data.Uid = uid.(int)

	// 判断评论id是否存在
	_,code := model.GetCommentPraiseInfo(data.CommentId)
	if code != errmsg.SUCCSE{
		c.JSON(http.StatusOK, gin.H{
			"status":code,
			"message":errmsg.GetErrorMsg(code),
		})
		return
	}

	praiseComment,code := model.IsPraiseComment(data.Uid,data.CommentId) // 查询用户是否点赞了评论
	fmt.Printf("u123:%#v\n",praiseComment)
	// 点赞
	if data.Status == 0{
		if code == errmsg.SUCCSE{
			if praiseComment.Status == 1{
				model.SaveCommentPraise(&data,data.Uid) // 更新评论点赞
			}
		}else{
			code = model.CreateCommentPraise(&data) // 没有数据，点赞成功
		}
	}else{
		// 取消点赞
		if code == errmsg.SUCCSE{
			if praiseComment.Status == 0{
				model.SaveCommentPraise(&data,data.Uid) // 更新评论点赞
			}
		}else{
			code = errmsg.ERROR // 操作失败
		}
	}
	c.JSON(http.StatusOK, gin.H{
		"status":code,
		"message":errmsg.GetErrorMsg(code),
	})

}